import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lcapp/api/interface/home_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/model/db/search_db_operate.dart';
import 'package:lcapp/model/toast/toast.dart';
import 'package:lcapp/page/search/search_user_page.dart';
import 'package:lcapp/page/search/search_video_page.dart';
import 'package:lcapp/page/search/search_xianhuo_page.dart';
import 'package:lcapp/page/search/search_zixun_page.dart';
import 'package:lcapp/widget/asr_app_bar.dart';

class SearchPage extends StatefulWidget {
  final int type; //0全局 1现货
  const SearchPage({Key? key, this.type=0}) : super(key: key);

  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> with SingleTickerProviderStateMixin{
  TextEditingController controller = TextEditingController();
  late TabController tabController;
  bool isSearch = false;
  int tabIndex = 0;
  List histories = [];
  List hots = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.type!=1){
      tabController = TabController(length: 4, vsync: this);
      getSearchHistory();
      getSearchHots();
    }else{
      isSearch = true;
      tabController = TabController(length: 1, vsync: this);
    }


  }

  //获取搜索历史
  void getSearchHistory() {
    SearchHistoryDB.getHistory('home').then((data) {
      if (data != null) {
        histories = data;
        setState(() {});
      }
    });
  }

  //获取搜索感兴趣
  void getSearchHots() async{
    ResponseData res = await HomeAPI.getSearchValues();
    if(res.code==200){
      setState(() {
        hots = res.data??[];
      });
    }
  }

  startSearch()async{
    if(controller.text.trim().isEmpty){
      showToast("输入您想要“搜索”的内容");
      return;
    }
    setState(() {
      isSearch = true;
    });
    if(widget.type==1){
      return;
    }
    SearchHistoryDB.operateRecord(
        {"record": controller.text, "module": 'home'});
    HomeAPI.addSearchValue(controller.text);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xffF4F4F4),
      appBar: AsrAppBar(
        titleText: "搜索",
        actions: [
          GestureDetector(
            onTap: (){
              Navigator.of(context).pushNamed('MobileScannerPage');
          },
            child: Container(
              margin: EdgeInsets.only(right: 30.w),
              child: Image.asset("assets/slider/slider_sys.png",width: 40.w,),
            ),
          )
        ],
      ),
      body: GestureDetector(
        onTap: (){
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 40.w),
          padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: 1.sw-60.w,
                height: 100.w,
                margin: EdgeInsets.only(top: 40.w),
                padding: EdgeInsets.symmetric(horizontal: 30.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(120.w)
                ),
                child: Row(
                  children: [
                    Expanded(child: TextField(
                      controller: controller,
                      textInputAction: TextInputAction.done,
                      maxLines: 1,
                      autocorrect: true,
                      autofocus: false,
                      decoration:  InputDecoration(
                        contentPadding: EdgeInsets.only(left: 17.w),
                        hintText: "输入您想要“搜索”的内容",
                        hintStyle: TextStyle(
                          color: const Color(0xFFAEAEAE),
                          fontSize: 26.sp,
                          fontWeight: FontWeight.w500,
                        ),
                        counterText: "",
                        border: const OutlineInputBorder(
                          borderSide: BorderSide.none,
                        ),
                        fillColor: Colors.transparent,
                        filled: true,
                      ),
                    ),),
                    GestureDetector(
                      onTap: (){
                        FocusScope.of(context).requestFocus(FocusNode());
                        startSearch();
                      },
                      child: Container(
                        margin: EdgeInsets.only(left: 10.w),
                        child: Image.asset("assets/home/search_red.png",width: 45.w,),
                      ),
                    )
                  ],
                ),
              ),
              Visibility(child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    margin: EdgeInsets.only(top: 60.w,bottom: 30.w),
                    child: Text('搜索历史',style: TextStyle(
                        color: Colors.black,
                        fontSize: 40.sp,
                        fontWeight: FontWeight.w700
                    ),),
                  ),
                  Container(
                    child: Wrap(
                      children: searchs(1),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 30.w,bottom: 30.w),
                    child: Text('可能感兴趣',style: TextStyle(
                        color: Colors.black,
                        fontSize: 40.sp,
                        fontWeight: FontWeight.w700
                    ),),
                  ),
                  Container(
                    child: Wrap(
                      children: searchs(2),
                    ),
                  ),
                ],
              ),visible: !isSearch,),
              Expanded(
                  child: Visibility(
                    child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                   Visibility(child: Container(
                     // color:Colors.red,
                     margin: EdgeInsets.only(top: 60.w,),
                     child: Row(
                       mainAxisAlignment: MainAxisAlignment.spaceBetween,
                       children: [
                         GestureDetector(
                           onTap: (){
                             if(tabIndex!=0){
                               setState(() {
                                 tabIndex=0;
                               });
                               tabController.index=0;
                             }

                           },
                           child: Container(
                             width: 120.w,
                             height: 60.w,
                             alignment: Alignment.center,
                             decoration: BoxDecoration(
                                 color: tabIndex==0?Colors.white:Colors.transparent,
                                 border: Border.all(color:tabIndex==0?Colors.white: Color(0xff797979),width: 1),
                                 borderRadius: BorderRadius.circular(10.w)
                             ),
                             child: Text('视频',style: TextStyle(
                                 color: Color(0xff333333),
                                 fontSize: 24.sp
                             ),),
                           ),
                         ),
                         GestureDetector(
                           onTap: (){
                             if(tabIndex!=1){
                               setState(() {
                                 tabIndex=1;
                               });
                               tabController.index=1;
                             }
                           },
                           child: Container(
                             width: 120.w,
                             height: 60.w,
                             alignment: Alignment.center,
                             decoration: BoxDecoration(
                                 color: tabIndex==1?Colors.white:Colors.transparent,
                                 border: Border.all(color:tabIndex==1?Colors.white: Color(0xff797979),width: 1),
                                 borderRadius: BorderRadius.circular(10.w)
                             ),
                             child: Text('资讯',style: TextStyle(
                                 color: Color(0xff333333),
                                 fontSize: 24.sp
                             ),),
                           ),
                         ),
                         GestureDetector(
                           onTap: (){
                             if(tabIndex!=2){
                               setState(() {
                                 tabIndex=2;
                               });
                               tabController.index=2;
                             }
                           },
                           child: Container(
                             width: 120.w,
                             height: 60.w,
                             alignment: Alignment.center,
                             decoration: BoxDecoration(
                                 color: tabIndex==2?Colors.white:Colors.transparent,
                                 border: Border.all(color:tabIndex==2?Colors.white: Color(0xff797979),width: 1),
                                 borderRadius: BorderRadius.circular(10.w)
                             ),
                             child: Text('现货',style: TextStyle(
                                 color: Color(0xff333333),
                                 fontSize: 24.sp
                             ),),
                           ),
                         ),
                         GestureDetector(
                           onTap: (){
                             if(tabIndex!=3){
                               setState(() {
                                 tabIndex=3;
                               });
                               tabController.index=3;
                             }
                           },
                           child: Container(
                             width: 120.w,
                             height: 60.w,
                             alignment: Alignment.center,
                             decoration: BoxDecoration(
                                 color: tabIndex==3?Colors.white:Colors.transparent,
                                 border: Border.all(color:tabIndex==3?Colors.white: Color(0xff797979),width: 1),
                                 borderRadius: BorderRadius.circular(10.w)
                             ),
                             child: Text('用户',style: TextStyle(
                                 color: Color(0xff333333),
                                 fontSize: 24.sp
                             ),),
                           ),
                         ),
                       ],
                     ),
                   ),visible: widget.type!=1,),
                   SizedBox(height: 30.w,),
                   Expanded(child: TabBarView(
                    physics: const NeverScrollableScrollPhysics(),
                      children: widget.type==1? [
                        SearchXHPage(searchValue: controller.text,),
                      ]:[
                     SearchVideoPage(searchValue: controller.text,),
                     SearchZXPage(searchValue: controller.text,),
                     SearchXHPage(searchValue: controller.text,),
                     SearchUserPage(searchValue: controller.text,)
                   ],
                    controller: tabController,
                  )
                  )
                ],
              ),
                    visible: isSearch,))
            ],
          ),
        ),
      ),
    );
  }

  List<Widget> searchs(int type){
    List<Widget> arr = [];
    if(type==1){
      for (var data in histories) {
        arr.add(
            searchItem(data['record'])
        );
      }
    }else{
      for (var data in hots) {
        arr.add(
            searchItem(data)
        );
      }
    }
    return arr;
  }
  
  Widget searchItem(String name){
    return GestureDetector(
      onTap: (){
        controller.text = name;
        startSearch();
      },
      child: Container(
        margin: EdgeInsets.only(right: 30.w,bottom: 30.w),
        padding: EdgeInsets.only(left: 25.w,top: 15.w,bottom: 15.w,right: 25.w),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(50.w)
        ),
        child: RichText(
          text: TextSpan(children: [
            TextSpan(
              text: name,
              style: TextStyle(
                fontSize: 24.sp,
                color: Color(0xFF333333),
                //height: 3,
              ),
            ),
            // WidgetSpan(
            //   child: GestureDetector(
            //     onTap: () {
            //       SearchHistoryDB.deleteRecord(data["id"]).then((val) {
            //         getSearchHistory();
            //       });
            //     },
            //     child: Container(
            //       //color: Colors.amber,
            //       padding: EdgeInsets.only(
            //         left: 5,
            //         right: 8,
            //       ),
            //       child: Icon(
            //         Icons.close,
            //         size: 16,
            //         color: Color(0xFF999999),
            //       ),
            //     ),
            //   ),
            // ),
          ]),
        ),
      ),
    );
  }

}
